package de.fhtrier.mp.wollmaus.gamestate;

import java.io.IOException;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.loading.DeferredResource;
import org.newdawn.slick.loading.LoadingList;
import org.newdawn.slick.state.StateBasedGame;

import de.fhtrier.mp.wollmaus.gamestate.menus.MenuState;
import de.fhtrier.mp.wollmaus.util.AssetManager;

public class LoadingState extends AbstractState {

	private Image bgImage;
	private final int MAX_WIDTH = 250;
	private DeferredResource nextResource;

	@Override
	public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
		bgImage = new Image("Files/img/loading.jpg");
		LoadingList.setDeferredLoading(true);

		AssetManager.getInstance();
		
		AbstractState s = new IntroState();
		sbg.addState(s);
		s.init(gc, sbg);
		s = new MenuState();
		sbg.addState(s);
		s.init(gc, sbg);
		s = new GameState();
		sbg.addState(s);
		s.init(gc, sbg);
	}

	@Override
	public int getID() {
		return 3;
	}

	@Override
	public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
		bgImage.draw();

		int total = LoadingList.get().getTotalResources();
		int loaded = LoadingList.get().getTotalResources() - LoadingList.get().getRemainingResources();

		int x = gc.getWidth() / 2 - (MAX_WIDTH / 2);

		g.setColor(Color.darkGray);
		g.fillRect(x - 1, 650 - 1, MAX_WIDTH + 2, 25 + 2);
		g.setColor(Color.black);
		g.fillRect(x, 650, MAX_WIDTH, 25);

		g.setColor(new Color(200, 0, 0));
		g.fillRect(x, 650, MAX_WIDTH * (loaded * 1f / total), 25);
	}

	@Override
	public void enter(GameContainer gc, StateBasedGame sbg) throws SlickException {
	}

	@Override
	public void leave(GameContainer gc, StateBasedGame sbg) throws SlickException {
	}

	@Override
	public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
		super.update(gc, sbg, delta);
		if (nextResource != null) {
			try {
				nextResource.load();
			}
			catch (IOException e) {
				throw new SlickException("Failed to load: " + nextResource.getDescription(), e);
			}
			nextResource = null;
		}

		if (LoadingList.get().getRemainingResources() > 0) {
			nextResource = LoadingList.get().getNext();
		}
		else {
			sbg.enterState(2);
		}
	}

}
